/**
 * Copyright (c) 2024 OSFW
 */
;(function($) {
    "use strict";

    $.fn.osfwStepProcess = function(options) {
        var target = $(this).data('step');
        target = target ? target : $(this);
        // 如果是调用方法
        if (typeof options == 'string') {
            if (arguments.length > 0) {
                if(Array.prototype.slice.call(arguments, 1).length > 1){
                    return $.fn.osfwStepProcess.methods[options](target, Array.prototype.slice.call(arguments, 1));
                }else {
                    return $.fn.osfwStepProcess.methods[options](target, Array.prototype.slice.call(arguments, 1)[0]);
                }
            }else {
                return $.fn.osfwStepProcess.methods[options](target, arguments);
            }
        }
        // 如果是初始化组件treegrid
        options = $.extend({}, $.fn.osfwStepProcess.defaults, options || {});
        target.isModified = options.isModified;
        var init = function (data) {
            // 初始化样式
            target.empty();
            var $ul = $('<ul class="progressbar"></ul>');
            var nextNodeKey;
            for(var i = 0; i < data.nodeDataArray.length; i++) {
                // 找下一个节点
                var nodeData, linkData;
                if(i == 0) {
                    nodeData = $.grep(data.nodeDataArray, function (item) { return item.category == 'Start'; })[0];
                }else {
                    nodeData = $.grep(data.nodeDataArray, function (item) { return item.key == nextNodeKey; })[0];
                }
                // 绘制节点
                var $li = $('<li id="'+nodeData.key+'" class="active"></li>');
                $li.append('<span class="before" data-key="' + nodeData.key + '" data-name="'+nodeData.text+'" data-category="'+nodeData.category+'" title="'+nodeData.text+'">'+nodeData.text+'</span>');
                if (target.isModified && nodeData.category !== 'End') {
                    $li.append('<a class="add-btn" onclick="$.step.insertStep(this)" data-key="' + nodeData.key + '" title="添加节点">+</a>');
                }
                $ul.append($li);
                // 设置下一节点key
                if(nodeData.category != 'End') {
                    linkData = $.grep(data.linkDataArray, function (item) { return item.from == nodeData.key; })[0];
                    nextNodeKey = linkData.to;
                }
            }
            target.append($ul);
            target.osfwStepProcess("resize");
            // 缓存target对象
            target.data_obj = data;
            target.data('step', target);
            return target.data_obj;
        };
        // 初始化
        init(options.data);

        return target;
    };

    $.fn.osfwStepProcess.defaults = {
        data: null,                // 构造流程的数据对象
        currentNode: null,         // 当前流转的流程节点
        isModified: true,          // 流程是否可编辑修改
        callback: function (res) {
            return false;
        }
    };

    $.fn.osfwStepProcess.methods = {
        fromJson: function (a) {
            var c = null;
            if ("string" == typeof a) {
                if (window.JSON && window.JSON.parse) {
                    try {
                        c = window.JSON.parse(a)
                    } catch (d) {
                        window.console && window.console.error("Error: JSON.parse error");
                    }
                } else {
                    window.console && window.console.warn("WARNING: no JSON.parse available");
                }
            } else if("object" == typeof a) {
                c = a;
            }else {
                window.console && window.console.error("Unable to construct a Model from: " + a);
            }
            return c;
        },
        resize: function (target) {
            // 计算宽度
            var _width = target.width() / target.find("ul.progressbar li").length - 20;
            target.find("ul.progressbar li").css("width", (_width) +'px');
            if(target.find("ul.progressbar li").length == 2){
                target.find("ul.progressbar li:after,ul.progressbar li:after").css("width", 'calc(100% - 60px)');
                target.find("ul.progressbar li:after,ul.progressbar li:after").css("left", 'calc((-100% + 60px) / 2)');
            }
        },
        toJson: function (target) {
            if(target.data_obj.nodeDataArray.length <= 2) {
                $.modal.alertError("请配置流程节点后重试");
            }else {
                return JSON.stringify(target.data_obj);
            }
        },
        /**
         * 插入节点
         */
        insert: function (target, params) {
            var from_ = params[0] + '';
            var nodeData_ = params[1];
            // 添加新的节点数据
            target.data_obj.nodeDataArray.push(nodeData_);
            // 调整连接线
            var prevLinkData = $.grep(target.data_obj.linkDataArray, function (item) { return item.from == from_; })[0];
            prevLinkData.from = nodeData_.key;
            var newLinkData = {
                from: from_,
                to: nodeData_.key,
                fromPort: 'R',
                toPort: 'L'
            };
            target.data_obj.linkDataArray.push(newLinkData);

            // 绘制节点
            var $prevLi = target.find('ul.progressbar li#' + from_);
            var $insertLi = $('<li id="'+nodeData_.key+'" class="active"></li>');
            $insertLi.append('<span class="before" data-key="' + nodeData_.key + '" data-name="'+nodeData_.text+'" data-category="'+nodeData_.category+'" title="'+nodeData_.text+'">'+nodeData_.text+'</span>');
            if (target.isModified && nodeData_.category !== 'End') {
                $insertLi.append('<a class="add-btn" onclick="$.step.insertStep(this)" data-key="' + nodeData_.key + '" title="添加节点">+</a>');
            }
            $prevLi.after($insertLi);
            target.find("ul.progressbar li#End").addClass("hasnode");
            target.osfwStepProcess("resize");

            // 缓存target对象
            target.data('step', target);
        },

        /**
         * 修改节点
         */
        edit: function (target, nodeForm) {
            console.log(nodeForm);
            var key = nodeForm.key;
            // 处理模型数据
            if(key != nodeForm.newKey){
                var lenght = $.grep(target.data_obj.nodeDataArray, function(item) {return item.key == nodeForm.newKey;}).length;
                if(lenght > 0) {
                    $.modal.alertWarning("该节点KEY已存在，请重新定义KEY");
                    return false;
                }
                nodeForm.key = nodeForm.newKey;
                delete nodeForm.newKey;
                target.data_obj.nodeDataArray = $.grep(target.data_obj.nodeDataArray, function(item) {return item.key != key;});
                target.data_obj.nodeDataArray.push(nodeForm);
                var leftLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.to == key;})[0];
                leftLink.to = nodeForm.key;
                var rightLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.from == key;})[0];
                rightLink.from = nodeForm.key;
            }else {
                target.data_obj.nodeDataArray = $.grep(target.data_obj.nodeDataArray, function(item) {return item.key != key;});
                target.data_obj.nodeDataArray.push(nodeForm);
            }

            // 重绘节点信息
            var $editLi = target.find('ul.progressbar li#' + key);
            $editLi.attr('id', nodeForm.key);
            var $span = $editLi.find("span.before");
            $span.attr("title", nodeForm.text);
            $span.data("key", nodeForm.key);
            $span.data("name", nodeForm.text);
            $span.data("category", nodeForm.category);
            $span.text(nodeForm.text);
            var $a = $editLi.find("a.add-btn");
            $a.data("key", nodeForm.key);

            // 缓存target对象
            target.data('step', target);
        },

        /**
         * 删除节点
         */
        remove: function (target, key_) {
            // 处理模型数据
            target.data_obj.nodeDataArray = $.grep(target.data_obj.nodeDataArray, function(item) {return item.key != key_;});
            var leftLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.to == key_;})[0];
            var rightLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.from == key_;})[0];
            leftLink.to = rightLink.to;
            target.data_obj.linkDataArray = $.grep(target.data_obj.linkDataArray, function(item) {return item.from != key_;});
            // 删除节点元素
            var $delLi = target.find('ul.progressbar li#' + key_);
            $delLi.remove();
            var nodeCount = target.find('ul.progressbar li:not(#Start,#End)').length;
            if(nodeCount == 0) {
                target.find('ul.progressbar li#End').removeClass('hasnode');
            }
            target.osfwStepProcess("resize");

            // 缓存target对象
            target.data('step', target);
        },

        /**
         * 向前移动
         */
        leftMove: function (target, key_) {
            // 处理模型数据
            var leftLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.to == key_;})[0];
            var rightLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.from == key_;})[0];
            var prevNode = $.grep(target.data_obj.nodeDataArray, function(item) {return item.key == leftLink.from;})[0];
            if(prevNode.category == 'Start'){
                $.modal.alertWarning("当前已为第一流程节点，无法再向前调整");
                return false;
            }
            var leftLeftLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.to == prevNode.key;})[0];
            leftLeftLink.to = key_;
            leftLink.from = key_;
            leftLink.to = prevNode.key;
            rightLink.from = prevNode.key;
            // 移动节点元素
            var $moveLi = target.find('ul.progressbar li#' + key_);
            $moveLi.prev().before($moveLi);

            // 缓存target对象
            target.data('step', target);
        },

        /**
         * 向后移动
         */
        rightMove: function (target, key_) {
            // 处理模型数据
            var leftLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.to == key_;})[0];
            var rightLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.from == key_;})[0];
            var nextNode = $.grep(target.data_obj.nodeDataArray, function(item) {return item.key == rightLink.to;})[0];
            if(nextNode.category == 'End') {
                $.modal.alertWarning("当前已为最后流程节点，无法再向后调整");
                return false;
            }
            var rightRightLink = $.grep(target.data_obj.linkDataArray, function(item) {return item.from == nextNode.key;})[0];
            rightRightLink.from = key_;
            leftLink.to = nextNode.key;
            rightLink.from = nextNode.key;
            rightLink.to = key_;
            // 移动节点元素
            var $moveLi = target.find('ul.progressbar li#' + key_);
            $moveLi.next().after($moveLi);

            // 缓存target对象
            target.data('step', target);
        },

        /**
         * 下一步
         */
        next: function (target) {
            var index = this.find("li.active").length;
            if (index == this.find("li").length) {
                return;
            }
            this.find("li").eq(index).addClass("active");
        },

        /**
         * 上一步
         */
        previous: function () {
            var index = this.find("li.active").length;
            if (index == 1) {
                return;
            }
            this.find("li").eq(index - 1).removeClass("active");
        },

        /**
         * 去第几步
         * @param step
         */
        goto: function (step) {
            if (step < 0 || step > this.find("li").length) {
                return;
            }
            this.find("li").removeClass("active");
            var $target = this.find("li").eq(step - 1);
            $target.addClass("active");
            $target.prevAll("li").addClass("active");
        },

        /**
         * 获取节点数据
         * @param step
         */
        getInfo: function (step) {
            if (step < 0 || step > this.find("li").length) {
                return;
            }
            this.find("li").removeClass("active");
            var $target = this.find("li").eq(step - 1);
            $target.addClass("active");
            $target.prevAll("li").addClass("active");
        },

        /**
         * 更新节点数据
         * @param step
         */
        updateInfo: function (obj) {
            if (step < 0 || step > this.find("li").length) {
                return;
            }
            return options.steps[step];
            this.find("li").removeClass("active");
            var $target = this.find("li").eq(step - 1);
            $target.addClass("active");
            $target.prevAll("li").addClass("active");
        },
    };

    $(window).resize(function(){
        var target =  $(".steps").data('step');
        target.init(target.data_obj);
    });

}($));
